﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NPipeline.Stage
{

    // this class should probably not even implement the IStage interface ...
    // only provide utility functions (like the Emit)
    public abstract class BaseStage : IStage
    {
        protected IStageContext context;

        // Feeder for the next downstream stage in the pipeline.
        // this value is lazyly initialized in the process method
        protected IFeeder downstreamfeeder;


        #region IStage Members

        public virtual void Init(IStageContext context)
        {
            this.context = context;
        }

        
        public virtual void PreProcess()
        {
            // noop            
        }

        public virtual void Process(object obj)
        {
            this.Emit(obj);
        }

        public virtual void PostProcess()
        {
            // noop
        }

        public virtual void Release()
        {
            // noop
        }

        #endregion
        

        // Convenicen method to sent the obj to the next stages feeder
        public void Emit(object obj)
        {
            // do some logging ...
            // lazy initialize the downstream feeder
            // this makes the Pipeline Imutable after one run -- can't add another
            // stage -- so - always look it up for now
            // TODO:::: find a solution
            //if (downstreamfeeder == null) 
            //    this.downstreamfeeder = this.context.getDownstreamFeeder(this);
            //this.downstreamfeeder.Feed(obj);

            this.context.getDownstreamFeeder(this).Feed(obj);

        }

        // convenience method to emit the object to a Branch Pipeline
        public void Emit(String branch, object obj)
        {
            this.context.getBranchFeeder(branch).Feed(obj);
        }


    }
}
